package plugin

import (
	"errors"
	"fmt"
	"gitee.com/gitee-go/core/model/pipeline"
	"gitee.com/gitee-go/core/models"
	"gitee.com/gitee-go/dag-core/dag"
	"gitee.com/gitee-go/server/comm"
	"gopkg.in/yaml.v2"
	"strings"
)

// 解析插件,并且拼装命令
func ParsingPlugin(job *models.Job, mjob map[string]interface{}, pl *models.Plugin) ([]interface{}, map[string]string, error) {
	if job.Job == "" {
		return nil, nil, errors.New("step 不能为空")
	}
	if pl.Type != "shell@bash" && pl.Type != "shell@sh" {
		return nil, nil, fmt.Errorf("插件%s只允许shell@bash或者shell@sh", job.Job)
	}
	toMap := jobToMap(mjob)
	marshal, err := yaml.Marshal(pl.Parameters)
	if err != nil {
		return nil, nil, fmt.Errorf("插件%s转换失败", job.Job)
	}
	err = dag.CheckPlugin(toMap, marshal)
	if err != nil {
		return nil, nil, err
	}
	parameters := pl.Parameters
	beforeCommand := pl.BeforeCommand
	afterCommand := pl.AfterCommand
	var command []interface{}
	for k, v := range toMap {
		p, ok := parameters[k]
		if !ok {
			delete(toMap, k)
			continue
		}
		if p.Type == "shell" {
			delete(toMap, k)
			if v != "" {
				err = yaml.Unmarshal([]byte(v), &command)
				if err != nil {
					return nil, nil, err
				}
			}
			break
		}
	}

	var cmds = beforeCommand
	if command != nil {
		cmds = append(cmds, command...)
	}
	if afterCommand != nil {
		cmds = append(cmds, afterCommand...)
	}
	if cmds == nil {
		return nil, nil, nil
	}
	return cmds, toMap, nil
}

func jobToMap(m map[string]interface{}) map[string]string {
	vm := map[string]string{}
	for k, v := range m {
		if k != "" && v != nil {
			vm[k] = fmt.Sprintf("%v", v)
		}
	}
	return vm
}

func GetDBPlugin(pluginName string) (*models.Plugin, error) {
	tp := &pipeline.TPlugin{}
	split := strings.Split(pluginName, "@")
	if len(split) != 2 {
		return nil, fmt.Errorf("%s插件格式错误", pluginName)
	}
	get, err := comm.DBMain.GetDB().Where("types = ? and name = ?", split[0], split[1]).Get(tp)
	if err != nil {
		return nil, err
	}
	if !get {
		return nil, nil
	}
	if tp.Content == "" {
		return nil, fmt.Errorf("%s插件yml内容为空", pluginName)
	}
	p := &models.Plugin{}
	err = yaml.Unmarshal([]byte(tp.Content), p)
	if err != nil {
		return nil, err
	}
	return p, err
}
